package bro2Advanced.threads;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 创建线程的三种方式
 * 一种是直接继承 Thread，一种是实现 Runnable 接口，另外一种是实现 Callable 接口。
 */

public class MyThread extends Thread {

    @Override
    public void run() {
        try {
            sleep(20);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        for (int i = 0; i < 100; i++) {
            System.out.println(getName() + "打了" + i + "小兵");
        }
    }

    public static void main(String[] args) {
//        MyThread t1 = new MyThread();
//        t1.setName("鲁班");
//        t1.start();
//
//        MyThread t2 = new MyThread();
//        t2.setName("张飞");
//        t2.start();

//        MyRunnable myRunnable = new MyRunnable();
//        Thread t1 = new Thread(myRunnable);
//        t1.start();
//        Thread t2 = new Thread(myRunnable);
//        t2.start();

        FutureTask<String> task = new FutureTask<>(new CallerTask());
        new Thread(task).start();

        String result = null;
        try {
            result = task.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {//sleep会发生异常要显示处理
                Thread.sleep(20);//暂停20毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "打了:" + i + "个小兵");
        }
    }
}

class CallerTask implements Callable<String> {

    @Override
    public String call() throws Exception {
        return "hello, i am running";
    }
}